Mathematical theory of democracy